from tencentcloud.common import credential
from tencentcloud.cdn.v20180606 import cdn_client
from tencentcloud.cdn.v20180606 import models

from logger import logger
from tools import ConfigTools


class TencentApiTools:

    def __init__(self, secret_id, secret_key):
        self.secret_id = secret_id
        self.secret_key = secret_key

    def describe_cdn_ip(self, ips):
        logger.info("describe_cdn_ip from TENCENT server: {}".format(ips))
        client_credential = credential.Credential(self.secret_id, self.secret_key)
        client = cdn_client.CdnClient(client_credential, "ap-beijing")
        describe_cdn_ip_request = models.DescribeCdnIpRequest()

        describe_cdn_ip_request.Ips = ips
        response = client.DescribeCdnIp(describe_cdn_ip_request)

        cdn_ips = []
        if len(response.Ips) > 0:
            for ip in response.Ips:
                if ip.Platform == 'yes':
                    cdn_ips.append(ip.Ip)
        else:
            raise RuntimeError("tencent api response no IPs, post ips: ", ips)

        return cdn_ips


if __name__ == '__main__':
    secret_id, secret_key = ConfigTools().read_config("tencent.common.SecretId", "tencent.common.SecretKey")
    ips = ['140.249.242.181', '101.89.239.168', '119.167.231.9', '119.167.231.40', '140.249.242.141', '140.249.242.150', '101.91.94.151', '140.249.242.182', '140.249.242.146', '140.249.242.144', '59.83.217.55', '180.96.55.147', '59.83.217.121', '180.96.55.164', '59.83.217.56', '119.167.231.41', '157.255.131.176', '180.96.55.151']
    print(TencentApiTools(secret_id, secret_key).describe_cdn_ip(ips))

